<template>
  <el-skeleton :loading="loading" animated>
    <template #default>
      <div class="item_center">
        <div class="box_size">
          <el-row :gutter="20">
            <!--            左侧商品图部分-->
            <el-col :span="8">
              <img-list :imgList="imgUrlList" v-if="showImg"></img-list>
            </el-col>
            <!--            右侧SKU信息以及销售属性部分-->
            <el-col :span="14">
              <div>
                <h2>{{ skuItemInfo?.skuInfo?.skuTitle }}</h2>
                <h5>{{ skuItemInfo?.skuInfo?.skuSubtitle }}</h5>
                <p style="color: red" v-if="saleFlashInfo!=null">
                  <span v-if="saleFlashInfo?.token">当前商品正在秒杀中热卖！快去抢购！ </span>
                  <span v-else>
                    当前商品即将投入秒杀！
                  </span>
                </p>
                <div>
                  <span class="price_class">￥{{
                      saleFlashInfo?.token == null ? skuItemInfo?.skuInfo?.price : saleFlashInfo?.price
                    }}</span>
                  &nbsp; &nbsp; 原价
                  <el-text v-if="saleFlashInfo?.token" tag="del" size="small">{{
                      skuItemInfo?.skuInfo?.price
                    }}
                  </el-text>
                </div>
                <div style="margin-top: 20px">
                  <div v-for="item in skuItemInfo?.skuItemSaleAttrVos" :key="item.id">
                    <el-row :gutter="20">
                      <el-col :span="3">{{ item.attrName }}</el-col>
                      <el-col :span="4" v-for="(valueItem,i) in item.attValues" :key="i">
                        <button
                            :class="valueItem?.skuIds.indexOf(skuItemInfo.skuInfo?.id)!==-1 ? 'skuValue_act_class' : 'skuValue_inc_class'"
                            @click="selectItem(item,valueItem.skuIds)">{{ valueItem.attrValue }}
                        </button>
                      </el-col>
                    </el-row>
                    <hr>
                  </div>
                </div>
                <div style="margin-top: 40px">
                  库存:{{ skuItemInfo.skuStock }}
                </div>
                <div style="margin-top: 20px">
                  <el-input-number v-model="num"/>
                </div>
                <div style="margin-top: 50px">
                  <button class="button button2" @click="addCart"><span>加入购物车</span></button>
                  <button class="button button2" @click="toConfirmOrder(0)" v-if="!saleFlashInfo?.token">
                    <span>立即购买</span></button>
                  <button class="button button2" @click="toConfirmOrder(1)" v-else><span style="color: red">立即抢购</span></button>
                  <button class="button button2" @click="goToCustomerService"><span>联系客服</span></button>
                </div>
              </div>
            </el-col>
          </el-row>
          <!--        下侧SPU、规格、售后、评价部分-->
          <el-row class="msg_box" :gutter="20">
            <el-col :span="5">
              <div style="text-align: center;background-color: #098CC0;color: white;padding: 5px">
                店铺精选
              </div>
              <div>
                <div v-for="item in otherSkus" style="margin-top: 10px;text-align: center">
                  <div class="item_center">
                    <el-image :src="$img+item.skuDefaultImg" style="height: auto;width: 150px"></el-image>
                  </div>
                  <div>
                    <el-text type="danger" size="large">
                      {{ item.price }}
                    </el-text>
                  </div>
                </div>
              </div>
            </el-col>
            <el-col :span="19">
              <div>
                <el-row>
                  <el-col :span="4" :class=" showComponentData===0 ? 'active_class': 'no_active'"><span
                      @click="showComponents(0)">商品介绍</span></el-col>
                  <el-col :span="4" :class=" showComponentData===1 ? 'active_class': 'no_active'"><span
                      @click="showComponents(1)">规格与包装</span></el-col>
                  <el-col :span="4" :class=" showComponentData===2 ? 'active_class': 'no_active'"><span
                      @click="showComponents(2)">售后保障</span></el-col>
                  <el-col :span="4" :class=" showComponentData===3 ? 'active_class': 'no_active'"><span
                      @click="showComponents(3)">商品评价</span></el-col>
                </el-row>
                <hr>
              </div>
              <div class="item_center">
                <div class="box_size">
                  <!--      商品介绍-->
                  <spu-describes
                      v-if="showComponentData===0" :descInfo="skuItemInfo"></spu-describes>
                  <!--      规格与包装-->
                  <spu-specification
                      :group-data="skuItemInfo.groupAttrs"
                      v-else-if="showComponentData===1"
                  ></spu-specification>
                  <!--          商品评价-->
                  <div v-else-if="showComponentData===2">
                    <div>
                      <el-image :src="require('@/assets/shouhou.jpg')"></el-image>
                    </div>
                  </div>
                  <appraise-list :skuId="skuItemInfo.skuInfo.id" v-else-if="showComponentData===3"/>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </template>
    <!--      骨架屏内容-->
    <template #template>
      <div style="height: 100%">
        <el-row :gutter="20">
          <el-col :span="7" :offset="1">
            <el-skeleton-item variant="image" style="height: 500px"/>
          </el-col>
          <el-col :span="13" :offset="1">
            <div>
              <el-skeleton-item variant="text" style="width: 100%;height: 40px"/>
              <el-skeleton-item variant="text" style="width: 100%;height: 40px;margin-top: 20px"/>
              <div style="margin-top: 30px">
                <span class="price_class"><el-skeleton-item variant="text" style="height: 30px;width: 80%"/></span>
              </div>
              <div style="margin-top: 150px">
                <div v-for="item in 2" :key="item">
                  <el-row :gutter="20">
                    <el-col :span="16">
                      <el-skeleton-item variant="text" style="height: 30px"/>
                    </el-col>
                  </el-row>
                </div>
              </div>
              <el-row style="margin-top: 20px">
                <el-col :span="12">
                  <el-skeleton-item variant="text" style="height: 30px"/>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>
      </div>
    </template>
  </el-skeleton>
</template>

<script setup>
import SpuDescribes from '@/components/commodity/SpuDescribes'
import SpuSpecification from '@/components/commodity/SpuSpecification'
import AppraiseList from '@/components/commodity/AppraiseList'
import {ref, onMounted,} from "vue";
import {useRoute, useRouter} from "vue-router";
import {getSkuItemApi, getStoreOtherSkus,} from "@/api/goods";
import ImgList from "@/components/commodity/ImgList";
import {addCartApi} from '@/api/cart'
import {ElMessage, ElMessageBox} from 'element-plus'
import {getFlashSaleSkuInfoBySkuId} from "@/api/flashSale";

let loading = ref(true)
const route = useRoute()
const router = useRouter()
let imgUrlList = ref([])
let skuItemInfo = ref({})
let showComponentData = ref(-1)//由于子组件需要父组件传递数据，需要确保父组件数据准备好了再加载子组件
let num = ref(1)
let showImg = ref(false)
let otherSkus = ref([])
let saleFlashInfo = ref()

onMounted(() => {
  window.scrollTo(0, 0);
  if (route.query.skuId) {
    getSkuItem(route.query.skuId)
  }
  storeOtherSkus()
  getIsFlashSale()
  setTimeout(() => {
    loading.value = false
  }, 1000)
})

function getSkuItem(skuId) {
  getSkuItemApi(skuId).then(res => {
    skuItemInfo.value = res.data
    skuItemInfo.value?.skuItemSaleAttrVos.forEach(attr => {
      attr.attValues.forEach(item => {
        if (item.skuIds.indexOf(skuItemInfo.value.skuInfo.id) !== -1) {
          attr.selectSkuList = [...item.skuIds]//赋值，但是不引用地址值
        }
      })
    })
    /*获取图片路径*/
    let imgIds = res.data.skuImags.map(item => {
      return item.imgId
    })
    imgUrlList.value = [...imgIds]
    showImg.value = true
  }).then(() => {
    showComponentData.value = 0//父组件数据已经准备妥当，加载子组件
  })
}

/**
 * 添加到购物车
 */
function addCart() {
  addCartApi(skuItemInfo.value.skuInfo?.id, num.value)
  router.push("/person/person-cart")
}

function toConfirmOrder(type) {
  if (skuItemInfo.value.skuStock - num.value < 0) {
    return ElMessage({message: "库存不足", type: 'error'})
  }
  //前往确认订单页面,传递参数：选择的skuid，购买的件数
  let data = {
    skuId: skuItemInfo.value.skuInfo.id,//选择的sku
    buyNumber: num.value,//购买的件数,
    token: saleFlashInfo.value.token
  }
  router.push({
    path: '/order-confirm',
    query: {
      type: type,
      data: JSON.stringify([data])
    }
  })
}

function getIsFlashSale() {
  getFlashSaleSkuInfoBySkuId(route.query.skuId).then(res => {
    saleFlashInfo.value = res.data
  })
}

function selectItem(selectGroup, skuIds) {
  /*先赋值，然后计算*/
  selectGroup.selectSkuList = skuIds
  /*遍历所有的分组，获取选中的skuid，然后计算出交集*/
  let arr = skuItemInfo.value?.skuItemSaleAttrVos.map(item => {
    return item.selectSkuList
  })
  //得出当前的skuId
  let findSkuId = findIntersection(arr)
  getSkuItem(findSkuId)
  //修改路由上的query值
  router.push({
    query: {
      skuId: findSkuId
    }
  })
}

function storeOtherSkus() {
  getStoreOtherSkus(route.query.skuId).then(res => {
    otherSkus.value = res.data
  })
}

/**
 * 获取传入的数组中的交集的值
 * @param arrays
 * @returns {null}
 */
function findIntersection(arrays) {
  // 创建一个 Set 对象来存储所有数组中的唯一元素
  let set = new Set();
  // 遍历每个数组，将其中的元素添加到 Set 对象中
  for (let array of arrays) {
    for (let element of array) {
      set.add(element);
    }
  }
  // 找到交集元素，即唯一存在于所有数组中的元素
  let intersection = null;
  for (let element of set) {
    if (arrays.every(array => array.includes(element))) {
      intersection = element;
      break;
    }
  }
  return intersection;
}

function goToCustomerService() {
  ElMessageBox.alert('功能还未实现', '警告', {
    confirmButtonText: '确定',
  })
}

function showComponents(v) {
  showComponentData.value = v
}
</script>

<style scoped>
.price_class {
  font-size: 30px;
  color: red;
}

.active_class {
  color: #288FC7;
}

.box_size {
  width: 1200px;
}

.msg_box {
  margin-top: 100px;
}

.item_center {
  display: flex;
  justify-content: center;
}

.skuValue_act_class {
  background-color: #098CC0;
  /*color: red;*/
}

.no_active:hover {
  color: red;
}

.cart_btn_msg {
  color: white;
}

.button {
  width: 150px;
  height: 50px;
  background-color: #288FC7;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
  -webkit-transition-duration: 0.4s;
  transition-duration: 0.4s;
}

.button2:hover {
  box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24), 0 17px 50px 0 rgba(0, 0, 0, 0.19);
  background-color: #1DAEEE;
  color: red;
}
</style>
